<?php 
## include required files
/*******************************/
require_once '../../includefiles.php';
require_once '../../model/users.php';
require_once '../../model/membershipplan.php';
require_once '../../model/state.php';
require_once '../../model/city.php';
include_once("../../model/usermembership.php");
include_once("../../model/usermembershipdetail.php");
require_once '../../includes/classes/paypalfunction.php'; // Pay Pal pro Function file 
require_once '../../model/admindetails.php';
include_once '../../model/email.php';
include_once '../../model/paypal.php';
include_once '../../model/trade.php';

$objPlan = new Model_PLAN();
$objState = new Model_State();
$objCity = new Model_City();
$memberObj	= new Model_Membership();
$memberDetailObj = new Model_MembershipDetail();
$userObj = new Model_Users();
$adminObj = new Model_AdminDetails();
$emailObj = new Model_Email();
$paypalObj = new Model_Paypal();

$tradeObj = new Model_TRADE();


if(!$_SESSION['pregister'] && $_POST)
{
	header("Location: ".SITE_URL."/");
	exit;		
}
$payvars = $_SESSION['pregister'];
$finalTotal= $payvars['totalcost'];

if($payvars["info"]['method'] == 'paypal')
{
	if($_POST['payment_status']=='Completed')
	{
		//build user info
		$userDetArray = array();
		$userDetArray['salutation'] 		= $payvars['info']['salutation'];
		$userDetArray["first_name"] 		= $payvars['info']['firstname'];
		$userDetArray["last_name"]			= $payvars['info']['lastname'];					
		$userDetArray["email"] 				= $payvars['info']['email'];
		$userDetArray['username'] 			= $payvars['info']['email'];
		$userDetArray['gender'] 			= $payvars['info']['gender'];					
		$userDetArray['password'] 			= md5($payvars['info']['password']);
		$userDetArray['phone_number'] 		= $payvars['info']['mobno'];					
		$userDetArray['companyname'] 		= $payvars['info']['companyname'];
		$userDetArray['postalcode'] 		= $payvars['info']['postcode'];					
		$userDetArray['birth_date'] 		= $payvars['info']['year']."-".$payvars['info']['month']."-".$payvars['info']['day'] ;
		
		$tempjobtype = array();
		$temptrades = array();
		foreach($payvars['cats'] as $pcat)
		{
			$temptrades[] = $pcat['id'];
			foreach($pcat['data'] as $chcat)
			{
				$tempjobtype[] = $chcat['id'];
			}
		}
		
		$userDetArray["tradeid"] 			= @implode(",",$temptrades);
		$userDetArray["jobtype"] 			= @implode(",",$tempjobtype);				
		$userDetArray["workarea"] 			= $payvars['info']['googlesearch'];		
		$userDetArray["centerpt"] 			= $payvars['info']['centerpt'];								
		$userDetArray["radius"] 			= $payvars['info']['radius'];		
		
					
		$userDetArray["abn"] 			= $payvars['info']['abn'];								
		$userDetArray["acn"] 			= $payvars['info']['acn'];					
		$userDetArray['user_type'] 		= 4;		
		$userDetArray["registered_date"] = getCurDate();
		// added expiry date
		$getplandetails = $objPlan->getPlanDetailsById($payvars['info']['plan_id']);
		$todaydate = date('Y-m-d');
		$exp_todaydate = explode('-',$todaydate);
		$userDetArray['expiry_date'] = date('Y-m-d',mktime(0,0,0,$exp_todaydate[1]+$getplandetails['month'],$exp_todaydate[2],$exp_todaydate[0]));
		$userDetArray["leads"] 			= $getplandetails['leads'];							
		$userDetArray["user_status"] 	= 0;	
		$userId = $userObj->addUserByValue($userDetArray);
		
		/************ Add record to membership plan Table ************/
		$membershipArray = array();
		$membershipArray['amount'] = $finalTotal;
		$membershipArray['user_id'] = $userId;
		$membershipArray['dateadded'] = date("Y-m-d H:i:s");
		$orderId = $memberObj->addOrder($membershipArray);
		
		$membershipplanArray 				    = 		array();	
		$membershipplanArray['user_id'] 			= 		$userId;
		$membershipplanArray['mem_id'] 			= 		$orderId;
		$membershipplanArray['plan_id'] 			= 		$payvars['info']['plan_id'];	
		$membershipplanArray['amount'] 	    	= 		$finalTotal;
		$membershipplanArray['add_date']   		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status_date'] 		= 		date("Y-m-d H:i:s");
		$getRandonUpper 					= 		strtoupper(getRandomNumber());
		$invoiceId 							= 		$payvars['invoice'];
		$orderCardArray['invoiceid']		= 		$invoiceId;
		$transactionId 						= 		$_REQUEST['TRANSACTIONID'];
		$membershipplanArray['transaction_id']   =       $transactionId;	
		$membershipplanArray['transaction_msg']  =       $httpParsedResponseAr["L_LONGMESSAGE0"];	 			
		$membershipplanArray['invoiceid']        =       $invoiceId;	
		$membershipplanArray['status_date']		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status'] 			= 		"paid";
		$membershipplanArray['paymentfor'] 			= 		"membershipplan";
		$membershipplanArray['pmethod'] 			= 		"Paypal";
		$orderDealId 			    		= 		$memberDetailObj->addRecord($membershipplanArray); // add order
		/*********record added to membership plan***********/
		
		
		/*   update trade category */
		$trades = array();
		foreach($payvars['cats'] as $pcat)
		{
			foreach($pcat['data'] as $chcat)
			{
				$trades[] = array("id"=>$chcat['id'],"expired_time"=>$chcat['expired_time']);	
				$order_items = array();
				$order_items['order_id'] = $orderDealId;
				$order_items['name'] = $chcat['trade_category'];
				$order_items['price'] = $chcat['price'];
				$order_items['type'] = "category" ;
				$tradeObj->addOrderItems($order_items);
			}
		}
		$tradeObj->updateUserTrades($userId,$trades);
		/* work area */
		if($payvars['info']['state_id'])
		{
			foreach($payvars['info']['state_id'] as $stateid)
			{
				$workArr = array();	
				$latlang				= @explode(',',$per);
				$workArr['user_id']		= $userId;
				$workArr['state_id']		= $stateid;
				$workArr['added_on']	= getCurDate();
				$workAreaId				= $userObj->addWorkAreaByValue($workArr);
			}
		}

		/* update order */
		/* update membership */
		$order_items = array();
		$order_items['order_id'] = $orderDealId;
		$order_items['name'] = "Membership Plan:" .$getplandetails["name"];
		$order_items['price'] = $getplandetails["price"];
		$order_items['type'] = "membership" ;
		$tradeObj->addOrderItems($order_items);
		
		
		// send email message to user
		$email_message = $emailObj->getEmailById(1);
		$e_subject = $email_message['email_subject'];
		$message = $email_message['email_content']; 
		$activationLink = SITE_URL."/signin/".md5($userId)."/activation/";		 
		$activationLink = '<a href="'.$activationLink.'">'.$activationLink.'</a>';		 
		$subject = str_replace('[SITENAME]', SITENAME, $e_subject);		 
		
		$message = str_replace('[NAME]', trim($payvars['info']["firstname"])." ".trim($payvars['info']["lastname"]) , $message);
		$message = str_replace('[SITENAME]', SITENAME, $message);
		$message = str_replace('[USERNAME]', trim($payvars['info']["email"]), $message);
		$message = str_replace('[PASSWORD]', trim($payvars['info']["password"]), $message); 
		$message = str_replace('[ACTIVATIONURL]', $activationLink, $message);
		$message = str_replace('[SITE_LINK]', SITENAME, $message);
		
		$to= trim($payvars['info']["email"]);
		$adminEmail = $adminObj->getAdminDetails();
		$from = $adminEmail;
		$fromname= SITENAME;
						 
		$emailTemplate = file_get_contents('../../emailtemplate.html');
		$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
		$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
		$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
		//echo $template_msg; exit;
		if(trim($to) != '')
		{
			//make pdf invoice
			$files = makeInvoicePDF($userId,$orderDealId);
			//@send_mail($to, $template_msg, $subject, $from, $fromname); 
			$mailer = new AttachMailer( $from,$to, $subject, $template_msg,$fromname);
			$mailer->attachFile($files[0].$files[1]);
			$mailer->send();
		}
		
		//message to admin
		//User REgister an acocunt (27)
		$email_message = $emailObj->getEmailById(27);
		$e_subject = $email_message['email_subject'];
		$message = $email_message['email_content']; 
		
		$subject = str_replace('[SITENAME]', SITENAME, $e_subject);		 
		$message = str_replace('[SITENAME]', SITENAME, $message);			
		$message = str_replace('[USERNAME]', $userDetArray["email"], $message);
		
		
		$message = str_replace('[FIRST_NAME]',$userDetArray["first_name"] , $message);
		$message = str_replace('[LAST_NAME]',$userDetArray["last_name"] , $message);
		$message = str_replace('[EMAIL]',$userDetArray["email"] , $message);
		$message = str_replace('[POSTAL_CODE]',$userDetArray["postalcode"] , $message);
		$message = str_replace('[MEMBERSHIP_PLAN]',$userDetArray["membership"] , $message);
		
		$message = str_replace('[SITE_LINK]', SITENAME, $message);
		
		$to= $email_message['from_email']; 
		$from = $email_message['from_email']; ;
		$fromname= SITENAME;
						 
		$emailTemplate = file_get_contents('emailtemplate.html');
		$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
		$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
		$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
		
		//echo $template_msg; exit;
		if(trim($to) != '')
		@send_mail($to, $template_msg, $subject, $from, $fromname); 
		
		
		unset($_SESSION['pregister']['cats']);
		unset($_SESSION['pregister']['info']);
		unset($_SESSION['pregister']['card']);
		
		header("Location: ".SITE_URL."/register/registersuccess/");
			
	}
	else
	{
		unset($_SESSION['pregister']['cats']);
		unset($_SESSION['pregister']['info']);
		unset($_SESSION['pregister']['card']);
		$_SESSION['msg'] = "<div class='success_msg'><span>Payment fail</span></div>";		

		header("Location: ".SITE_URL);
		exit;	
	}
}
else //nab
{
		//build user info
		$userDetArray = array();
		$userDetArray['salutation'] 		= $payvars['info']['salutation'];
		$userDetArray["first_name"] 		= $payvars['info']['firstname'];
		$userDetArray["last_name"]			= $payvars['info']['lastname'];					
		$userDetArray["email"] 				= $payvars['info']['email'];
		$userDetArray['username'] 			= $payvars['info']['email'];
		$userDetArray['gender'] 			= $payvars['info']['gender'];					
		$userDetArray['password'] 			= md5($payvars['info']['password']);
		$userDetArray['phone_number'] 		= $payvars['info']['mobno'];					
		$userDetArray['companyname'] 		= $payvars['info']['companyname'];
		$userDetArray['postalcode'] 		= $payvars['info']['postcode'];					
		$userDetArray['birth_date'] 		= $payvars['info']['year']."-".$payvars['info']['month']."-".$payvars['info']['day'] ;
		
		$tempjobtype = array();
		$temptrades = array();
		foreach($payvars['cats'] as $pcat)
		{
			$temptrades[] = $pcat['id'];
			foreach($pcat['data'] as $chcat)
			{
				$tempjobtype[] = $chcat['id'];
			}
		}
		
		$userDetArray["tradeid"] 			= @implode(",",$temptrades);
		$userDetArray["jobtype"] 			= @implode(",",$tempjobtype);				
		$userDetArray["workarea"] 			= $payvars['info']['googlesearch'];		
		$userDetArray["centerpt"] 			= $payvars['info']['centerpt'];								
		$userDetArray["radius"] 			= $payvars['info']['radius'];		
		
					
		$userDetArray["abn"] 			= $payvars['info']['abn'];								
		$userDetArray["acn"] 			= $payvars['info']['acn'];					
		$userDetArray['user_type'] 		= 4;		
		$userDetArray["registered_date"] = getCurDate();
		// added expiry date
		$getplandetails = $objPlan->getPlanDetailsById($payvars['info']['plan_id']);
		$todaydate = date('Y-m-d');
		$exp_todaydate = explode('-',$todaydate);
		$userDetArray['expiry_date'] = date('Y-m-d',mktime(0,0,0,$exp_todaydate[1]+$getplandetails['month'],$exp_todaydate[2],$exp_todaydate[0]));
		$userDetArray["leads"] 			= $getplandetails['leads'];							
		$userDetArray["user_status"] 	= 0;	
		$userId = $userObj->addUserByValue($userDetArray);
		
		/************ Add record to membership plan Table ************/
		$membershipArray = array();
		$membershipArray['amount'] = $finalTotal;
		$membershipArray['user_id'] = $userId;
		$membershipArray['dateadded'] = date("Y-m-d H:i:s");
		$orderId = $memberObj->addOrder($membershipArray);
		
		$membershipplanArray 				    = 		array();	
		$membershipplanArray['user_id'] 			= 		$userId;
		$membershipplanArray['mem_id'] 			= 		$orderId;
		$membershipplanArray['plan_id'] 			= 		$payvars['info']['plan_id'];	
		$membershipplanArray['amount'] 	    	= 		$finalTotal;
		$membershipplanArray['add_date']   		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status_date'] 		= 		date("Y-m-d H:i:s");
		$getRandonUpper 					= 		strtoupper(getRandomNumber());
		$invoiceId 							= 		$payvars['invoice'];
		$orderCardArray['invoiceid']		= 		$invoiceId;
		$transactionId 						= 		$_REQUEST['TRANSACTIONID'];
		$membershipplanArray['transaction_id']   =       $transactionId;	
		$membershipplanArray['transaction_msg']  =       $httpParsedResponseAr["L_LONGMESSAGE0"];	 			
		$membershipplanArray['invoiceid']        =       $invoiceId;	
		$membershipplanArray['status_date']		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status'] 			= 		"paid";
		$membershipplanArray['paymentfor'] 			= 		"membershipplan";
		$membershipplanArray['pmethod'] 			= 		"NAB";
		$orderDealId 			    		= 		$memberDetailObj->addRecord($membershipplanArray); // add order
		/*********record added to membership plan***********/
		
		
		/*   update trade category */
		$trades = array();
		foreach($payvars['cats'] as $pcat)
		{
			foreach($pcat['data'] as $chcat)
			{
				$trades[] = array("id"=>$chcat['id'],"expired_time"=>$chcat['expired_time']);	
				$order_items = array();
				$order_items['order_id'] = $orderDealId;
				$order_items['name'] = $chcat['trade_category'];
				$order_items['price'] = $chcat['price'];
				$order_items['type'] = "category" ;
				$tradeObj->addOrderItems($order_items);
			}
		}
		$tradeObj->updateUserTrades($userId,$trades);
		/* work area */
		if($payvars['info']['state_id'])
		{
			foreach($payvars['info']['state_id'] as $stateid)
			{
				$workArr = array();	
				$latlang				= @explode(',',$per);
				$workArr['user_id']		= $userId;
				$workArr['state_id']		= $stateid;
				$workArr['latitude']	= $latlang[0];
				$workArr['longitude']	= $latlang[1];
				$workArr['added_on']	= getCurDate();
				$workAreaId				= $userObj->addWorkAreaByValue($workArr);
			}
		}
		/* update order */
		/* update membership */
		$order_items = array();
		$order_items['order_id'] = $orderDealId;
		$order_items['name'] = "Membership Plan:" .$getplandetails["name"];
		$order_items['price'] = $getplandetails["price"];
		$order_items['type'] = "membership" ;
		$tradeObj->addOrderItems($order_items);
		
		
		// send email message
		$email_message = $emailObj->getEmailById(1);
		$e_subject = $email_message['email_subject'];
		$message = $email_message['email_content']; 
		$activationLink = SITE_URL."/signin/".md5($userId)."/activation/";		 
		$activationLink = '<a href="'.$activationLink.'">'.$activationLink.'</a>';		 
		$subject = str_replace('[SITENAME]', SITENAME, $e_subject);		 
		
		$message = str_replace('[NAME]', trim($payvars['info']["firstname"])." ".trim($payvars['info']["lastname"]) , $message);
		$message = str_replace('[SITENAME]', SITENAME, $message);
		$message = str_replace('[USERNAME]', trim($payvars['info']["email"]), $message);
		$message = str_replace('[PASSWORD]', trim($payvars['info']["password"]), $message); 
		$message = str_replace('[ACTIVATIONURL]', $activationLink, $message);
		$message = str_replace('[SITE_LINK]', SITENAME, $message);
		
		$to= trim($payvars['info']["email"]);
		$adminEmail = $adminObj->getAdminDetails();
		$from = $adminEmail;
		$fromname= SITENAME;
						 
		$emailTemplate = file_get_contents('../../emailtemplate.html');
		$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
		$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
		$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
		//echo $template_msg; exit;
		if(trim($to) != '')
		{
			//make pdf invoice
			$files = makeInvoicePDF($userId,$orderDealId);
			//@send_mail($to, $template_msg, $subject, $from, $fromname); 
			$mailer = new AttachMailer( $from,$to, $subject, $template_msg,$fromname);
			$mailer->attachFile($files[0].$files[1]);
			$mailer->send();
		}
		
		
		//User REgister an acocunt (27)
		$email_message = $emailObj->getEmailById(27);
		$e_subject = $email_message['email_subject'];
		$message = $email_message['email_content']; 
		
		$subject = str_replace('[SITENAME]', SITENAME, $e_subject);		 
		$message = str_replace('[SITENAME]', SITENAME, $message);			
		$message = str_replace('[USERNAME]', $userDetArray["email"], $message);
		
		
		$message = str_replace('[FIRST_NAME]',$userDetArray["first_name"] , $message);
		$message = str_replace('[LAST_NAME]',$userDetArray["last_name"] , $message);
		$message = str_replace('[EMAIL]',$userDetArray["email"] , $message);
		$message = str_replace('[POSTAL_CODE]',$userDetArray["postalcode"] , $message);
		$message = str_replace('[MEMBERSHIP_PLAN]',$userDetArray["membership"] , $message);
		
		$message = str_replace('[SITE_LINK]', SITENAME, $message);
		
		$to= $email_message['from_email']; 
		$from = $email_message['from_email']; ;
		$fromname= SITENAME;
						 
		$emailTemplate = file_get_contents('emailtemplate.html');
		$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
		$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
		$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
		
		//echo $template_msg; exit;
		if(trim($to) != '')
		@send_mail($to, $template_msg, $subject, $from, $fromname); 		
		unset($_SESSION['pregister']['cats']);
		unset($_SESSION['pregister']['info']);
		unset($_SESSION['pregister']['card']);
		
		header("Location: ".SITE_URL."/register/registersuccess/");
}
exit;
?>

